package com.phiture.erp.stock.core.service.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.stock.core.pojo.dto.ErpStockPageReqDTO;
import com.phiture.erp.stock.core.service.ErpStockService;
import com.phiture.erp.stock.core.service.ErpWarehouseService;
import com.phiture.erp.stock.dal.entity.ErpStockDO;
import com.phiture.erp.stock.dal.mapper.ErpStockMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.phiture.erp.common.constants.ErrorCodeConstants.STOCK_COUNT_NEGATIVE;
import static com.phiture.erp.common.constants.ErrorCodeConstants.STOCK_COUNT_NEGATIVE2;

/**
 * @author YH
 * @date 2025/4/13
 */

@Service
@RequiredArgsConstructor
public class ErpStockServiceImpl implements ErpStockService {
    private final ErpStockMapper stockMapper;
    private final ErpWarehouseService warehouseService;
    private final ErpMaterialApi materialApi;

    /**
     * 允许库存为负数
     */
    private static final Boolean NEGATIVE_STOCK_COUNT_ENABLE = false;

    @Override
    public ErpStockDO getStock(Long id) {
        return stockMapper.selectById(id);
    }

    @Override
    public ErpStockDO getStock(Long materialId, Long warehouseId) {
        return stockMapper.selectByMaterialIdAndWarehouseId(materialId, warehouseId);
    }

    @Override
    public BigDecimal getStockCount(Long warehouseId, Long materialId) {
        BigDecimal count = stockMapper.selectSum(warehouseId, materialId);
        return count != null ? count : BigDecimal.ZERO;
    }

    @Override
    public PageResult<ErpStockDO> getStockPage(ErpStockPageReqDTO pageReqDTO) {
        return stockMapper.selectPage(pageReqDTO, new LambdaQueryWrapperX<ErpStockDO>()
                .eqIfPresent(ErpStockDO::getMaterialId, pageReqDTO.getMaterialId())
                .eqIfPresent(ErpStockDO::getWarehouseId, pageReqDTO.getWarehouseId())
                .orderByDesc(ErpStockDO::getId));
    }

    @Override
    public BigDecimal updateStockCountIncrement(Long materialId, Long warehouseId, BigDecimal count) {
        // 1.1 查询当前库存
        ErpStockDO stock = stockMapper.selectByMaterialIdAndWarehouseId(materialId, warehouseId);
        if (stock == null) {
            stock = new ErpStockDO().setMaterialId(materialId).setWarehouseId(warehouseId).setCount(BigDecimal.ZERO);
            stockMapper.insert(stock);
        }
        // 1.2 校验库存是否充足
        if (!NEGATIVE_STOCK_COUNT_ENABLE && stock.getCount().add(count).compareTo(BigDecimal.ZERO) < 0) {
            throw exception(STOCK_COUNT_NEGATIVE, materialApi.getMaterial(materialId).getName(),
                    warehouseService.getWarehouse(warehouseId).getName(), stock.getCount(), count);
        }

        // 2. 库存变更
        int updateCount = stockMapper.updateCountIncrement(stock.getId(), count, NEGATIVE_STOCK_COUNT_ENABLE);
        if (updateCount == 0) {
            // 此时不好去查询最新库存，所以直接抛出该提示，不提供具体库存数字
            throw exception(STOCK_COUNT_NEGATIVE2, materialApi.getMaterial(materialId).getName(),
                    warehouseService.getWarehouse(warehouseId).getName());
        }

        // 3. 返回最新库存
        return stock.getCount().add(count);
    }
}
